package org.jeecg.modules.payment.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.jeecg.common.config.TenantContext;
import org.jeecg.common.constant.CacheConstant;
import org.jeecg.common.desensitization.util.SensitiveInfoUtil;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.payment.constant.PaymentCacheConstant;
import org.jeecg.modules.payment.entity.PaymentConfig;
import org.jeecg.modules.payment.enums.PayChannelEnums;
import org.jeecg.modules.payment.mapper.PaymentConfigMapper;
import org.jeecg.modules.payment.service.IPaymentConfigService;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Description: 支付配置
 * @Author: sean
 * @Date:   2024-08-28
 * @Version: V1.0
 */
@Service
@RequiredArgsConstructor
public class PaymentConfigServiceImpl extends ServiceImpl<PaymentConfigMapper, PaymentConfig> implements IPaymentConfigService {

    private final CacheManager cacheManager;

    @Override
    public IPage<PaymentConfig> selectJoinPage(Page<PaymentConfig> page, Wrapper wrapper) {
        IPage<PaymentConfig> pageList = baseMapper.selectJoinPage(page, wrapper);
        if(ObjectUtil.isNotEmpty(pageList)){
            pageList.getRecords().stream().forEach(item->{
                item.setChannelName(PayChannelEnums.getEnumByValue(item.getChannelCode()).getLabel());
            });
        }
        return pageList;
    }

    @Override
    public PaymentConfig getConfigByChannel(String tenantId, String channelCode) {
        Cache cache = cacheManager.getCache(PaymentCacheConstant.PAYMENT_CONFIG_KEY);
        tenantId = oConvertUtils.isNotEmpty(tenantId) ? tenantId : TenantContext.getTenant();
        PaymentConfig config = cache.get(tenantId + ":" + channelCode, PaymentConfig.class);
        if(oConvertUtils.isEmpty(config)){
            config = baseMapper.getOneNoTenant(new QueryWrapper<PaymentConfig>()
                    .eq(ObjectUtil.isNotEmpty(tenantId) ,"tenant_id",tenantId)
                    .eq("channel_code",channelCode));
            if(oConvertUtils.isNotEmpty(config)){
                //加密
                try {
                    config = (PaymentConfig) SensitiveInfoUtil.handlerObject(config, true);
                    cache.put(TenantContext.getTenant()+":"+channelCode, config);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                }
            }
        }else{
            //解密
            try {
                config = (PaymentConfig) SensitiveInfoUtil.handlerObject(config, false);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }
        return config;
    }

    @Override
    public PaymentConfig add(PaymentConfig entity) {
        if(oConvertUtils.isEmpty(entity)){
            throw new JeecgBootException("提交了一个空内容,操作失败");
        }
        if(this.saveOrUpdate(entity)){
            Cache cache = cacheManager.getCache(PaymentCacheConstant.PAYMENT_CONFIG_KEY);
            //加密
            try {
                entity = (PaymentConfig) SensitiveInfoUtil.handlerObject(entity, true);
                cache.put(TenantContext.getTenant() + ":" + entity.getChannelCode(), entity);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }
        return entity;
    }

    @Override
    public PaymentConfig edit(PaymentConfig entity) {
        if(oConvertUtils.isEmpty(entity)){
            throw new JeecgBootException("提交了一个空内容,操作失败");
        }
        if(this.saveOrUpdate(entity)){
            Cache cache = cacheManager.getCache(PaymentCacheConstant.PAYMENT_CONFIG_KEY);
            //加密
            try {
                entity = (PaymentConfig) SensitiveInfoUtil.handlerObject(entity, true);
                cache.put(TenantContext.getTenant() + ":" + entity.getChannelCode(), entity);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }
        return entity;
    }

    @Override
    public Boolean delById(String id) {
        PaymentConfig paymentConfig = this.getById(id);
        // 构造需要删除的key，这里只是示例，实际key可能不同
        String keyToDelete = paymentConfig.getTenantId() + ":" + paymentConfig.getChannelCode();
        Cache cache = cacheManager.getCache(PaymentCacheConstant.PAYMENT_CONFIG_KEY);
        cache.evict(keyToDelete);
        return this.removeById(id);
    }

    @Override
    public Boolean delByIds(List<String> ids) {
        List<PaymentConfig> rentalConfigList = this.listByIds(ids);
        Cache cache = cacheManager.getCache(PaymentCacheConstant.PAYMENT_CONFIG_KEY);
        if (cache != null) {
            rentalConfigList.forEach(item->{
                String keyToDelete = item.getTenantId() + ":" + item.getChannelCode();
                cache.evict(keyToDelete);
            });
        }
        return this.removeByIds(ids);
    }




}
